﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Project_ScansiaPacific
{
    public partial class FrKV3_KTam : DevComponents.DotNetBar.Office2007Form
    {
        public FrKV3_KTam()
        {
            InitializeComponent();
        }
        private string MaSP1, TenSP1, MaCT1, TenCT1, SoBB1, SLNhap1, SLXuat1, Ngay_start1, Ngay_End1, child = " - ", Ngay1, NgayInsert1, UserNhap, UserXuat,LoaiGo1,GhiChu1,LyDo1,SoKH1,string_temp,ChungTu1;
        private double Tong1 = 0, SLNhap_d = 0, SLXuat_d = 0, TK_KTG;
        private int i = 0;
        private void combo_load()
        {
            Data dta = new Data();
            FormProcess Frp = new FormProcess();
            DataSet ds = new DataSet();
            string sql_load = @"select * from dbo.Load_cbSP";
            Frp.cb1(cb_MaSPinput, sql_load, 1, 0);
            Frp.cb1(cb_MaSPoutput, sql_load, 1, 0);
            Frp.cb1(cb_MaSPTK, sql_load, 1, 0);
            Frp.cb1(cb_MaSPReport, sql_load, 1, 0);
            Frp.cb1(cb_MaSP_C, sql_load, 1, 0);
            Frp.cb1(cb_MaSP_N, sql_load, 1, 0);
            //Frp.cb1(cb_TenSPKH, sql_load, 1, 0);
            string[] arr_LyDo = new string[] { "Lắp Ráp","Xưởng NT", "Gia Công","Hàng Tồn","Khác"};
            for (int j = 0; j < arr_LyDo.Length; j++)
            {
                cb_LyDoNhap.Items.Add(arr_LyDo[j].ToString());
                cb_LyDoXuat.Items.Add(arr_LyDo[j].ToString());
            }
            string_temp = @"select dbo.Load_CTSP_Mua.MaSP,dbo.Load_CTSP_Mua.TenChiTiet+' - '+dbo.Load_CTSP_Mua.MaChiTiet from dbo.Load_CTSP_Mua inner join dbo.ChiTiet_KhuVuc on ChiTiet_KhuVuc.MaCT=dbo.Load_CTSP_Mua.MaChiTiet and ChiTiet_KhuVuc.KhuVuc='KV3'";
            ds = dta.dts(string_temp);
            for (i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                dataGridView_LoadSP.Rows.Add(ds.Tables[0].Rows[i][0].ToString(), ds.Tables[0].Rows[i][1].ToString());
            }
            ds.Clear();


        }
        private void Enable()
        {
            tab_Nhap.Visible = true;
            tab_Xuat.Visible = true;

        }
        private void Disable()
        {
            tab_Nhap.Visible = false;
            tab_Xuat.Visible = false;
        }
        private void Check_User()
        {
            Process prs = new Process();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();
            try
            {
                Conn.Open();
                string check = @"select GroupUser from dbo.Users where UsersName='" + lb_user.Text + "'";
                cmd.Connection = Conn;
                cmd.CommandText = check;
                //MessageBox.Show(check);
                check = cmd.ExecuteScalar().ToString();
                if (check == "thongke" || check == "admin" || check == "nhaplieu")
                    Enable();
                else
                    Disable();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }

        private void cb_MaSPinput_SelectedIndexChanged(object sender, EventArgs e)
        {
            Process prs = new Process();
           
            MaSP1 = prs.substring_right(cb_MaSPinput.Text, child);
            cb_MaCTinput.Items.Clear();
            cb_MaCTinput.Text = "";
            for (i = dataGridView_LoadSP.Rows.Count - 2; i >= 0; i--)
            {
                if (MaSP1 == dataGridView_LoadSP.Rows[i].Cells[0].Value.ToString())
                {
                    cb_MaCTinput.Items.Add(dataGridView_LoadSP.Rows[i].Cells[1].Value.ToString());
                }
            }
        }

        private void txt_SLinput_TextChanged(object sender, EventArgs e)
        {
            FormProcess Frp = new FormProcess();
            Frp.checktext_number(txt_SLinput);
        }

        private void FrKV4_KTam_Load(object sender, EventArgs e)
        {
            combo_load();
        }
        private void add_grid()
        {
            try
            {
                Process prs = new Process();
                TenSP1 = prs.substring_left(cb_MaSPinput.Text, child);
                TenCT1 = prs.substring_left(cb_MaCTinput.Text, child);
                MaCT1 = prs.substring_right(cb_MaCTinput.Text, child);
                if (TenSP1 == "" || MaCT1 == "" || txt_Ngayinput.Text == "" || txt_SLinput.Text == ""||cb_LyDoNhap.Text=="")
                {
                    MessageBox.Show("Thông Tin Nhập Không Chính Xác Hoặc Thiếu");
                }
                else
                {
                    //SoKH1 = txt_SoKHinput.Text.Trim();
                    SoBB1 = txt_SoBBinput.Text.Trim();
                    //SL1 = txt_SLInput.Text.Trim();
                    Ngay1 = txt_Ngayinput.Text.Trim();
                    SLNhap1 = txt_SLinput.Text;
                    LoaiGo1 = txt_LoaiGoinput.Text;
                    string[] temp = txt_Ngayinput.Text.Split('/');
                    NgayInsert1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                    GhiChu1 = txt_GhiChuNhap.Text;
                    LyDo1 = cb_LyDoNhap.Text;
                    dataGridView1.Rows.Add(TenSP1, MaCT1, TenCT1,LoaiGo1, SoBB1, SLNhap1, Ngay1, NgayInsert1,LyDo1,GhiChu1);
                    //prs.reset_txt(groupPanel1);
                    txt_SLinput.Text = "";
                    cb_MaCTinput.Text = "";
                    Tong1 = double.Parse(lb_Tong.Text);
                    Tong1 += double.Parse(SLNhap1);
                    lb_Tong.Text = Tong1.ToString();
                    lb_Tong.Text = string.Format("{0:###,###}", Tong1);
                    cb_MaSPinput.Focus();
                    prs.formatcolordatagrid(dataGridView1);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_insertinput_Click(object sender, EventArgs e)
        {
            add_grid();
        }
        private void save_input()
        {
            
            Data dta = new Data();
            SqlConnection Conn = dta.Connect();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "Tran_Ins_Up_KTam";
            cmd.CommandType = CommandType.StoredProcedure;
            //string insert_NhapKTam = null;
            try
            {
                Conn.Open();
                cmd.Connection = Conn;
                if (dataGridView1.Rows.Count > 1)
                {
                    for (i = dataGridView1.Rows.Count - 2; i >= 0; i--)
                    {
                        MaCT1 = dataGridView1.Rows[i].Cells["MaCTinput"].Value.ToString();
                        //SoKH1 = dataGridView1.Rows[i].Cells["SoKH"].Value.ToString();
                        SoBB1 = dataGridView1.Rows[i].Cells["SoBBinput"].Value.ToString();
                        SLNhap_d = double.Parse(dataGridView1.Rows[i].Cells["SLInput"].Value.ToString());
                        LoaiGo1 = dataGridView1.Rows[i].Cells["LoaiGoinput"].Value.ToString();
                        Ngay1 = dataGridView1.Rows[i].Cells["Ngayinsert"].Value.ToString();
                        UserNhap = lb_user.Text;
                        GhiChu1 = dataGridView1.Rows[i].Cells["GhiChuNhap"].Value.ToString();
                        LyDo1 = dataGridView1.Rows[i].Cells["LyDoNhap"].Value.ToString();
                        cmd.Parameters.AddWithValue("@MaCT", MaCT1);
                        cmd.Parameters.AddWithValue("@SoBB", SoBB1);
                        cmd.Parameters.AddWithValue("@LoaiGo", LoaiGo1);
                        cmd.Parameters.AddWithValue("@SLNhap", SLNhap_d);
                        cmd.Parameters.AddWithValue("@Ngay", Ngay1);
                        cmd.Parameters.AddWithValue("@GhiChu", GhiChu1);
                        cmd.Parameters.AddWithValue("@LyDo", LyDo1);
                        cmd.Parameters.AddWithValue("@UserNhap", UserNhap);
                        cmd.Parameters.AddWithValue("@SLTheoDoi", SLNhap_d);
                        cmd.Parameters.AddWithValue("@ID", SoBB1);
                        //insert_NhapKTam = @"insert into dbo.KV4_KTam(MaCT,SoBB,LoaiGo,SLNhap,Ngay,GhiChu,LyDo,UserNhap)values(N'" + MaCT1 + "',N'" + SoBB1 + "',N'" + LoaiGo1 + "'," + SLNhap_d + ",'" + Ngay1 +"',N'"+GhiChu1+"',N'"+LyDo1+"',N'" + UserNhap + "')";
                        
                        //MessageBox.Show(insert_NhapKTG);
                        cmd.ExecuteNonQuery();
                        dataGridView1.Rows.RemoveAt(i);
                        cmd.Parameters.Clear();
                        
                    }
                    MessageBox.Show("Dữ Liệu được lưu thành công");
                    lb_Tong.Text = "0";
                    //dta.reset_txt(groupPanel1);
                    cb_MaSPinput.Text = "";
                    cb_MaCTinput.Text = "";
                    txt_SLinput.Text = "";
                    txt_SoBBinput.Text = "";
                    txt_GhiChuNhap.Text = "";
                }
            }
            catch (Exception ex)
            {
                string s = "insert duplicate key";
                string FK = "FOREIGN KEY constraint";
                string s1 = ex.Message.ToString();
                if (s1.Contains(s))
                { MessageBox.Show("Insert không thành công \n" + "Mã đã tồn tại "); }
                else if (s1.Contains(FK))
                { MessageBox.Show("Nhập sai thông tin trong Combobox"); }
                else
                    MessageBox.Show(ex.Message);
                MessageBox.Show("Đã xảy ra lỗi khi thêm dữ liệu, vui lòng kiểm tra lại");
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }

        private void bt_saveinput_Click(object sender, EventArgs e)
        {
            save_input();
        }
        private void edit_input()
        {
            try
            {
                string datecheck;
                int date_count;
                Process prs = new Process();
                SqlConnection Conn = prs.Connect();
                SqlCommand cmd = new SqlCommand();
                DialogResult d = MessageBox.Show("Bạn có chắc muốn sửa Thông Tin có Số Serial " + lb_serialinput.Text, "Thông Báo", MessageBoxButtons.OKCancel);
                MaCT1 = prs.substring_right(cb_MaCTinput.Text, child);
                Ngay1 = txt_Ngayinput.Text;
                SoBB1 = txt_SoBBinput.Text;
                LoaiGo1 = txt_LoaiGoinput.Text;
                //SoKH1 = txt_SoKHinput.Text;
                SLNhap_d = double.Parse(txt_SLinput.Text);
                GhiChu1 = txt_GhiChuNhap.Text;
                LyDo1 = cb_LyDoNhap.Text;
                string[] temp = Ngay1.Split('/');
                Ngay1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                Conn.Open();
                cmd.Connection = Conn;
                datecheck = @"select datediff(dd,NgayInsert,getdate()) from dbo.KV4_KTam where Serial='" + lb_serialinput.Text + "'";
                if (d == DialogResult.OK)
                {

                    cmd.CommandText = datecheck;
                    date_count = int.Parse(cmd.ExecuteScalar().ToString());
                    if (date_count <= 1)
                    {
                        if (MaCT1 != "" && txt_Ngayinput.Text != "" && txt_SLinput.Text != "" && cb_LyDoNhap.Text != "")
                        {
                            string update_XP = @"UPDATE [dbo].[KV4_KTam] SET MaCT='" + MaCT1 + "',SoBB='" + SoBB1 + "',LoaiGo='" + LoaiGo1 + "',SLNhap=" + SLNhap_d + ",Ngay='" + Ngay1 + "',GhiChu=N'" + GhiChu1 + "',LyDo=N'" + LyDo1 + "', Useredit='" + lb_user.Text + "' where Serial='" + lb_serialinput.Text + "'";
                            // MessageBox.Show(update_XP);
                            cmd.CommandText = update_XP;
                            cmd.ExecuteNonQuery();
                            MessageBox.Show("Chỉnh Sửa Thành Công");
                        }
                        else
                            MessageBox.Show("Nhập thiếu thông tin");
                    }
                    else
                        MessageBox.Show("Không được phép chỉnh sửa");
                    Conn.Close();
                    cmd.Dispose();
                    for (i = 0; i < dataGridView2.Rows.Count - 1; i++)
                    {
                        dataGridView2.Rows.RemoveAt(0);
                    }
                    prs.reset_txt(groupPanel1);
                    bt_editinput.Enabled = false;
                    bt_deleteinput.Enabled = false;
                    lb_serialinput.Text = "0";

                }
            }
            catch (Exception ex)
            {
                string s = "The conversion of a char data type to a datetime";
                string s1 = ex.Message.ToString();
                if (s1.Contains(s))
                { MessageBox.Show("Ngày Tháng Nhập chưa đúng"); }
                MessageBox.Show(ex.Message);
            }

        }
        private void Display_Input(int i)
        {
            try
            {
                MaSP1 = dataGridView2.Rows[i].Cells["MaSP"].Value.ToString();
                TenSP1 = dataGridView2.Rows[i].Cells["TenSP"].Value.ToString();
                MaCT1 = dataGridView2.Rows[i].Cells["MaCT"].Value.ToString();
                TenCT1 = dataGridView2.Rows[i].Cells["TenChiTiet"].Value.ToString();
                cb_MaSPinput.Text = TenSP1 + " - " + MaSP1;
                cb_MaCTinput.Text = TenCT1 + " - " + MaCT1;
                txt_SoBBinput.Text = dataGridView2.Rows[i].Cells["SoBB"].Value.ToString();
                txt_LoaiGoinput.Text = dataGridView2.Rows[i].Cells["LoaiGo"].Value.ToString();
                //txt_SoKHinput.Text = dataGridView2.Rows[i].Cells["SoKH"].Value.ToString();
                txt_SLinput.Text = dataGridView2.Rows[i].Cells["SLNhap"].Value.ToString();
                txt_Ngayinput.Text = dataGridView2.Rows[i].Cells["Ngay"].Value.ToString();
                txt_GhiChuNhap.Text = dataGridView2.Rows[i].Cells["GhiChu"].Value.ToString();
                cb_LyDoNhap.Text = dataGridView2.Rows[i].Cells["LyDo"].Value.ToString();
                lb_serialinput.Text = dataGridView2.Rows[i].Cells["Serial"].Value.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void search_Input()
        {
            try
            {
                string search = null;
                Process prs = new Process();
                DataSet ds = new DataSet();
                if (cb_MaCTinput.Text != "" && txt_Ngayinput.Text != "")
                {
                    MaCT1 = prs.substring_right(cb_MaCTinput.Text, child);
                    string[] temp = txt_Ngayinput.Text.Split('/');
                    Ngay1 = temp[1] + "/" + temp[0] + "/" + temp[2];

                    if (MaCT1 == "")
                        MessageBox.Show("Mã CT không chính xác");
                    else
                    {
                        search = @"select qry1.Serial,ChiTietSP.TenSP,ChiTietSP.MaSP,ChiTietSP.TenChiTiet,qry1.MaCT,qry1.SoBB,qry1.SoKH,qry1.SLNhap,qry1.Ngay,qry1.LoaiGo,qry1.GhiChu,LyDo from (select Serial,MaCT,SoBB,SoKH,LoaiGo,SLNhap,Ngay,GhiChu,LyDo from dbo.KV4_KTam where MaCT='" + MaCT1 + "' and Ngay='" + Ngay1 + "' and SLNhap is not null) as qry1 inner join dbo.ChiTietSP on qry1.MaCT=ChiTietSP.MaChiTiet";
                    }
                    ds = prs.dts(search);
                    if (ds.Tables[0].Rows.Count == 0)
                        MessageBox.Show("Không có dữ liệu, vui lòng kiểm tra lại thông tin tìm kiếm");
                    else
                    {
                        dataGridView2.DataSource = ds.Tables[0];
                        int k = dataGridView2.Rows.Count - 2;
                        Display_Input(k);
                        lb_index.Text = k.ToString();
                        bt_editinput.Enabled = true;
                        bt_deleteinput.Enabled = true;
                    }
                }
                else
                    MessageBox.Show("Bạn cần nhập Mã CT và Ngày để tìm kiếm");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_searchinput_Click(object sender, EventArgs e)
        {
            search_Input();
        }

        private void bt_previnput_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView2.Rows.Count > 0)
                {
                    
                    i = int.Parse(lb_index.Text);
                    if (i > 0)
                    {
                        i--;
                        Display_Input(i);
                        lb_index.Text = i.ToString();
                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void bt_nextinput_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView1.Rows.Count > 0)
                {
                   
                    i = int.Parse(lb_index.Text);
                    if (i < dataGridView2.Rows.Count - 2)
                    {
                        i++;
                        Display_Input(i);
                        lb_index.Text = i.ToString();
                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void bt_editinput_Click(object sender, EventArgs e)
        {
            edit_input();
        }

        private void bt_deleteinput_Click(object sender, EventArgs e)
        {
            DialogResult d = MessageBox.Show("Bạn có chắc muốn xóa Thông Tin có Số Serial " + lb_serialinput.Text, "Thông Báo", MessageBoxButtons.OKCancel);
            if (d == DialogResult.OK)
            {
                try
                {
                    string datecheck = @"select datediff(dd,NgayInsert,getdate()) from dbo.KV4_KTam where Serial='" + lb_serialinput.Text + "'";
                    string delete = @"delete from dbo.KV4_KTam where Serial='" + lb_serialinput.Text + "'";
                    Data dta = new Data();
                    SqlConnection Conn = dta.Connect();
                    Conn.Open();
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = Conn;
                    cmd.CommandText = datecheck;
                    int date_count = int.Parse(cmd.ExecuteScalar().ToString());
                    if (date_count <= 1 || lb_user.Text == "administrator")
                    {
                        cmd.CommandText = delete;
                        cmd.ExecuteNonQuery();
                        MessageBox.Show("Dữ liệu được xóa thành công");

                        lb_serialinput.Text = "0";
                    }
                    else
                    {
                        MessageBox.Show("Quá thời gian cho phép,Không được xóa");
                    }
                    Conn.Close();
                    cmd.Dispose();
                    for (i = 0; i < dataGridView2.Rows.Count - 1; i++)
                    {
                        dataGridView2.Rows.RemoveAt(0);
                    }
                    dta.reset_txt(groupPanel1);
                    bt_deleteinput.Enabled = false;
                    bt_editinput.Enabled = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        private void cb_MaSPoutput_SelectedIndexChanged(object sender, EventArgs e)
        {
            Process prs = new Process();
            
            MaSP1 = prs.substring_right(cb_MaSPoutput.Text, child);
            cb_MaCToutput.Items.Clear();
            cb_MaCToutput.Text = "";
            for (i = dataGridView_LoadSP.Rows.Count - 2; i >= 0; i--)
            {
                if (MaSP1 == dataGridView_LoadSP.Rows[i].Cells[0].Value.ToString())
                {
                    cb_MaCToutput.Items.Add(dataGridView_LoadSP.Rows[i].Cells[1].Value.ToString());
                }
            }
        }

        private void txt_SLoutput_TextChanged(object sender, EventArgs e)
        {
            try
            {
                FormProcess Frp = new FormProcess();
                Frp.checktext_number(txt_SLoutput);
                
            }
            catch
            {

            }
        }
        private void check_TonKho()
        {
            SLXuat_d = double.Parse(txt_SLoutput.Text);
            TK_KTG = double.Parse(lb_TonKho.Text);
            if (SLXuat_d > TK_KTG)
            {
                MessageBox.Show("SL xuất không vượt quá SL Tồn Kho");
                txt_SLoutput.Text = "";
            }
            else
            {
                TK_KTG = double.Parse(lb_SLKH.Text);
                if (SLXuat_d > TK_KTG)
                {
                    MessageBox.Show("SL xuất trong kế hoạch này không vượt quá " + lb_SLKH.Text);
                    txt_SLoutput.Text = "";
                }
            }
            
        }
        private void add_grid_out()
        {
            try
            {
                Process prs = new Process();
                TenSP1 = prs.substring_left(cb_MaSPoutput.Text, child);
                TenCT1 = prs.substring_left(cb_MaCToutput.Text, child);
                MaCT1 = prs.substring_right(cb_MaCToutput.Text, child);
                SoKH1 = prs.substring_right(cb_SoKHoutput.Text.Trim(), child);
                if (TenSP1 == "" || MaCT1 == "" || txt_Ngayoutput.Text == "" || txt_SLoutput.Text == ""||cb_LyDoXuat.Text==""||SoKH1=="")
                {
                    MessageBox.Show("Thông Tin Nhập Không Chính Xác Hoặc Thiếu");
                }
                else
                {
                    
                    //SL1 = txt_SLoutput.Text;
                    Ngay1 = txt_Ngayoutput.Text.Trim();
                    SLXuat1 = txt_SLoutput.Text.Trim();
                    LoaiGo1 = txt_LoaiGooutput.Text.Trim();
                    GhiChu1 = txt_GhiChuXuat.Text;
                    LyDo1 = cb_LyDoXuat.Text;
                    string[] temp = Ngay1.Split('/');
                    NgayInsert1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                    //i = 0;
                    /*if (dataGridView3.Rows.Count > 1)
                    {
                        while (i < dataGridView3.Rows.Count - 1)
                        {
                            if (MaCT1 != dataGridView3.Rows[i].Cells["MaCToutput"].Value.ToString())
                                i++;
                            else
                                break;
                        }
                    }*/
                  
                        dataGridView3.Rows.Add(MaSP1, MaCT1, TenCT1, LoaiGo1, SoKH1, SLXuat1, Ngay1, NgayInsert1,LyDo1,GhiChu1);
                        //prs.reset_txt(groupPanel1);
                        txt_SLoutput.Text = "";
                        cb_MaCToutput.Text = "";
                        txt_GhiChuXuat.Text = "";
                        lb_SLKH.Text = "0";
                        lb_TonKho.Text = "0";
                        cb_SoKHoutput.Items.Clear();
                        cb_SoKHoutput.Text = "";
                        Tong1 = double.Parse(lb_TongXuat.Text);
                        Tong1 += double.Parse(SLXuat1);
                        lb_TongXuat.Text = Tong1.ToString();
                        lb_Tong.Text = string.Format("{0:###,###}", Tong1);
                        cb_MaSPoutput.Focus();
                        prs.formatcolordatagrid(dataGridView3);
                   
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_insertoutput_Click(object sender, EventArgs e)
        {
            add_grid_out();
        }
        private void save_output()
        {
            
            Data dta = new Data();
            SqlConnection Conn = dta.Connect();
            SqlCommand cmd = new SqlCommand();
            
            Conn.Open();
            cmd.Connection = Conn;

           // string insert_XuatKTG, update_TheoDoiKH;
            try
            {
                cmd.CommandText = @"select max(ChungTu)+1 from dbo.KV4_KTam";
                ChungTu1 = cmd.ExecuteScalar().ToString();
                
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "Tran_Ins_Up_KTamX";
                if (dataGridView3.Rows.Count > 1)
                {
                    for (i = dataGridView3.Rows.Count - 2; i >= 0; i--)
                    {
                        MaCT1 = dataGridView3.Rows[i].Cells["MaCToutput"].Value.ToString();
                       
                        SoKH1 = dataGridView3.Rows[i].Cells["SoKHoutput"].Value.ToString();
                        LoaiGo1 = dataGridView3.Rows[i].Cells["LoaiGooutput"].Value.ToString();
                        SLXuat_d = double.Parse(dataGridView3.Rows[i].Cells["SLoutput"].Value.ToString());
                        Ngay1 = dataGridView3.Rows[i].Cells["NgayInsert_out"].Value.ToString();
                        GhiChu1 = dataGridView3.Rows[i].Cells["GhiChuXuat"].Value.ToString();
                        LyDo1 = dataGridView3.Rows[i].Cells["LyDoXuat"].Value.ToString();
                        UserXuat = lb_user.Text;
                        cmd.Parameters.AddWithValue("@MaCT", MaCT1);
                        cmd.Parameters.AddWithValue("@ChungTu", ChungTu1);
                        cmd.Parameters.AddWithValue("@SoKH", SoKH1);
                        cmd.Parameters.AddWithValue("@LoaiGo", LoaiGo1);
                        cmd.Parameters.AddWithValue("@SLXuat", SLXuat_d);
                        cmd.Parameters.AddWithValue("@Ngay", Ngay1);
                        cmd.Parameters.AddWithValue("@GhiChu", GhiChu1);
                        cmd.Parameters.AddWithValue("@LyDo", LyDo1);
                        cmd.Parameters.AddWithValue("@UserNhap  ", UserXuat);
                        cmd.Parameters.AddWithValue("@SLTheoDoi", SLXuat_d);
                        cmd.Parameters.AddWithValue("@ID", SoKH1);
                        //MessageBox.Show(insert_NhapKTG);
                        
                        cmd.ExecuteNonQuery();
                        
                        dataGridView3.Rows.RemoveAt(i);
                        cmd.Parameters.Clear();
                    }
                    MessageBox.Show("Dữ Liệu được lưu thành công");
                    lb_TongXuat.Text = "0";
                    cb_MaCToutput.Text = "";
                    cb_MaSPoutput.Text = "";
                    txt_SLoutput.Text = "";
                    cb_SoKHoutput.Text = "";
                    txt_GhiChuXuat.Text = "";
                    txt_SoPhieu_print.Text=ChungTu1;
                    cb_MaSPoutput.Focus();
                    
                    
                }
            }
            catch (Exception ex)
            {
                string s = "insert duplicate key";
                string FK = "FOREIGN KEY constraint";
                string s1 = ex.Message.ToString();
                if (s1.Contains(s))
                { MessageBox.Show("Insert không thành công \n" + "Mã đã tồn tại "); }
                else if (s1.Contains(FK))
                { MessageBox.Show("Nhập sai thông tin trong Combobox"); }
                else
                    MessageBox.Show(ex.Message);
                MessageBox.Show("Đã xảy ra lỗi khi thêm dữ liệu, vui lòng kiểm tra lại");
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }

        private void bt_saveoutput_Click(object sender, EventArgs e)
        {
            save_output();
        }
        private void edit_output()
        {
            try
            {
                string datecheck;
                int date_count;
                Process prs = new Process();
                SqlConnection Conn = prs.Connect();
                SqlCommand cmd = new SqlCommand();
                DialogResult d = MessageBox.Show("Bạn có chắc muốn sửa Thông Tin có Số Serial " + lb_serialout.Text, "Thông Báo", MessageBoxButtons.OKCancel);
                MaCT1 = prs.substring_right(cb_MaCToutput.Text, child);
                Ngay1 = txt_Ngayoutput.Text;
                SoKH1 = cb_SoKHoutput.Text;
                //SoKH1 = txt_SoKHoutput.Text;
                LoaiGo1 = txt_LoaiGooutput.Text;
                SLXuat_d = double.Parse(txt_SLoutput.Text);
                string[] temp = Ngay1.Split('/');
                Ngay1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                GhiChu1 = txt_GhiChuXuat.Text;
                LyDo1 = cb_LyDoXuat.Text;
                Conn.Open();
                cmd.Connection = Conn;
                datecheck = @"select datediff(dd,NgayInsert,getdate()) from dbo.KV4_KTam where Serial='" + lb_serialout.Text + "'";
                if (d == DialogResult.OK)
                {
                    cmd.CommandText = datecheck;
                    date_count = int.Parse(cmd.ExecuteScalar().ToString());
                    if (date_count <= 1)
                    {
                        if (MaCT1 != "" && txt_SLoutput.Text != "" && txt_Ngayoutput.Text != "")
                        {
                            string update_XP = @"UPDATE [dbo].[KV4_KTam] SET MaCT='" + MaCT1 + "',SoKH='" + SoKH1 + "',LoaiGo='" + LoaiGo1 + "',SLXuat=" + SLXuat_d + ",Ngay='" + Ngay1 + "',LyDo=N'"+LyDo1+"',GhiChu=N'" + GhiChu1 + "',Useredit='" + lb_user.Text + "' where Serial='" + lb_serialout.Text + "'";
                            // MessageBox.Show(update_XP);
                            cmd.CommandText = update_XP;
                            cmd.ExecuteNonQuery();
                            MessageBox.Show("Chỉnh Sửa Thành Công");
                        }
                        else
                            MessageBox.Show("Nhập thiếu thông tin");
                    }
                    else
                        MessageBox.Show("Không được phép chỉnh sửa");
                    Conn.Close();
                    cmd.Dispose();
                    for (i = 0; i < dataGridView4.Rows.Count - 1; i++)
                    {
                        dataGridView4.Rows.RemoveAt(0);
                    }
                    //dataGridView4.Rows.Clear();
                    prs.reset_txt(groupPanel3);
                    bt_editoutput.Enabled = false;
                    bt_deleteoutput.Enabled = false;
                    lb_serialout.Text = "0";
                }
            }
            catch (Exception ex)
            {
                string s = "The conversion of a char data type to a datetime";
                string s1 = ex.Message.ToString();
                if (s1.Contains(s))
                { MessageBox.Show("Ngày Tháng Nhập chưa đúng"); }
                MessageBox.Show(ex.Message);
            }

        }
        private void Display_output(int i)
        {
            try
            {

                MaSP1 = dataGridView4.Rows[i].Cells["MaSP"].Value.ToString();

                TenSP1 = dataGridView4.Rows[i].Cells["TenSP"].Value.ToString();

                MaCT1 = dataGridView4.Rows[i].Cells["MaCT"].Value.ToString();

                TenCT1 = dataGridView4.Rows[i].Cells["TenChiTiet"].Value.ToString();

                cb_MaSPoutput.Text = TenSP1 + " - " + MaSP1;
                cb_MaCToutput.Text = TenCT1 + " - " + MaCT1;
                cb_SoKHoutput.Text = dataGridView4.Rows[i].Cells["SoKH"].Value.ToString();
               // txt_SoKHoutput.Text = dataGridView4.Rows[i].Cells["SoKH"].Value.ToString();
                txt_LoaiGooutput.Text = dataGridView4.Rows[i].Cells["LoaiGo"].Value.ToString();
                txt_SLoutput.Text = dataGridView4.Rows[i].Cells["SLXuat"].Value.ToString();
                txt_Ngayoutput.Text = dataGridView4.Rows[i].Cells["Ngay"].Value.ToString();
                txt_GhiChuXuat.Text = dataGridView4.Rows[i].Cells["GhiChu"].Value.ToString();
                cb_LyDoXuat.Text = dataGridView4.Rows[i].Cells["LyDo"].Value.ToString();
                lb_serialout.Text = dataGridView4.Rows[i].Cells["Serial"].Value.ToString();
                lb_SLXuat.Text = dataGridView4.Rows[i].Cells["SLXuat"].Value.ToString();
                lb_SoKH.Text = dataGridView4.Rows[i].Cells["SoKH"].Value.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void search_Output()
        {
            try
            {
                string search = null;
                Process prs = new Process();
                DataSet ds = new DataSet();
                    if (cb_MaCToutput.Text != "" && txt_Ngayoutput.Text != "")
                    {
                        MaCT1 = prs.substring_right(cb_MaCToutput.Text, child);
                        string[] temp = txt_Ngayoutput.Text.Split('/');
                        Ngay1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                    }
                    if (MaCT1 == "")
                        MessageBox.Show("Mã CT không chính xác");
                    else
                    {
                        search = @"select qry1.Serial,ChiTietSP.TenSP,ChiTietSP.MaSP,ChiTietSP.TenChiTiet,qry1.MaCT,qry1.SoKH,qry1.LoaiGo,qry1.SLXuat,qry1.Ngay,qry1.GhiChu,qry1.LyDo from (select Serial,MaCT,SoKH,LoaiGo,SLXuat,Ngay,GhiChu,LyDo from dbo.KV4_KTam where MaCT='" + MaCT1 + "' and Ngay='" + Ngay1 + "' and SLXuat is not null) as qry1 inner join dbo.ChiTietSP on qry1.MaCT=ChiTietSP.MaChiTiet";
                    }
                    MessageBox.Show(search);
                ds = prs.dts(search);
                if (ds.Tables[0].Rows.Count == 0)
                    MessageBox.Show("Không có dữ liệu, nhập Ngày và Tên Chi Tiết để tìm kiếm");
                else
                {
                    dataGridView4.DataSource = ds.Tables[0];
                    int k = dataGridView4.Rows.Count - 2;
                    //lb_TonKho.Text = "1000000";
                    Display_output(k);
                    lb_indexout.Text = k.ToString();
                    bt_editoutput.Enabled = true;
                    bt_deleteoutput.Enabled = true;

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_searchoutput_Click(object sender, EventArgs e)
        {
            search_Output();
        }

        private void bt_prevoutput_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView4.Rows.Count > 0)
                {
                    
                    i = int.Parse(lb_indexout.Text);
                    if (i > 0)
                    {
                        i--;
                        Display_output(i);
                        lb_indexout.Text = i.ToString();
                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void bt_nextoutput_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView4.Rows.Count > 0)
                {
                    
                    i = int.Parse(lb_indexout.Text);
                    if (i < dataGridView4.Rows.Count - 2)
                    {
                        i++;
                        Display_output(i);
                        lb_indexout.Text = i.ToString();
                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void bt_editoutput_Click(object sender, EventArgs e)
        {
            //edit_output();
            MessageBox.Show("Hiện tại chức năng này chưa sử dụng được, Bạn có thể xóa dữ liệu trước sau đó nhập mới lại");
        }

        private void bt_deleteoutput_Click(object sender, EventArgs e)
        {
            DialogResult d = MessageBox.Show("Bạn có chắc muốn xóa Thông Tin có Số Serial " + lb_serialout.Text, "Thông Báo", MessageBoxButtons.OKCancel);
            string update_TheoDoiKH = null;
            SoKH1 = lb_SoKH.Text;
            if (d == DialogResult.OK)
            {
                try
                {
                    SLXuat_d = double.Parse(lb_SLXuat.Text);
                    string datecheck = @"select datediff(dd,NgayInsert,getdate()) from dbo.KV4_KTam where Serial='" + lb_serialout.Text + "'";
                    update_TheoDoiKH = @"UPDATE [dbo].[KH_Theodoi] SET [SLTheoDoi] = SLTheoDoi+" + SLXuat_d + " WHERE ID='" + SoKH1 + "'";
                    string delete = @"delete from dbo.KV4_KTam where Serial='" + lb_serialout.Text + "'";
                    Data dta = new Data();
                    SqlConnection Conn = dta.Connect();
                    Conn.Open();
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = Conn;
                    cmd.CommandText = datecheck;
                    int date_count = int.Parse(cmd.ExecuteScalar().ToString());
                    if (date_count <= 1 || lb_user.Text == "administrator")
                    {
                        cmd.CommandText = delete;
                        cmd.ExecuteNonQuery();
                        cmd.CommandText = update_TheoDoiKH;
                        cmd.ExecuteNonQuery();
                        MessageBox.Show("Dữ liệu được xóa thành công");
                        lb_serialinput.Text = "0";
                        lb_SLXuat.Text = "0";
                        lb_SoKH.Text = "";
                    }
                    else
                    {
                        MessageBox.Show("Quá thời gian cho phép,Không được phép xóa");
                    }
                    Conn.Close();
                    cmd.Dispose();
                    for (i = 0; i < dataGridView4.Rows.Count - 1; i++)
                    {
                        dataGridView4.Rows.RemoveAt(0);
                    }
                    dta.reset_txt(groupPanel3);
                    bt_deleteoutput.Enabled = false;
                    bt_editoutput.Enabled = false;

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        
        private void TonKho()
        {
            Process prs = new Process();
            FormProcess Frp = new FormProcess();
            SqlConnection Conn = prs.Connect();

            SqlCommand cmd = new SqlCommand();
            try
            {
                Conn.Open();
                cmd.Connection = Conn;
                MaCT1 = prs.substring_right(cb_MaCToutput.Text, child);
                string TonKho = @"select TonKho from dbo.KTam_TK where MaCT='" + MaCT1 + "'";
                cmd.CommandText = TonKho;
                lb_TonKho.Text = cmd.ExecuteScalar().ToString();
                cb_SoKHoutput.Items.Clear();
                cb_SoKHoutput.Text = "";
                TonKho = @"select left(ID_KeHoach,5),ID from KH_TheoDoi where SLTheoDoi>0 and MaCT='"+MaCT1+"' and ID_KeHoach like '%KV3%'";
                Frp.cb1(cb_SoKHoutput, TonKho,0,1);

                
            }
            catch
            {
                //MessageBox.Show(ex.Message);
                lb_TonKho.Text = "0";
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }

        }
        private void search_TK()
        {
            try
            {
                string searchTK = null;
                Process prs = new Process();
                if (cb_MaSPTK.Text == "" && cb_MaCTTK.Text == "")
                {
                    searchTK = @"select TenSP,TenChiTiet,TonKho from dbo.KTam_TK";
                }
                if (cb_MaSPTK.Text != "" & cb_MaCTTK.Text == "")
                {
                    MaSP1 = prs.substring_right(cb_MaSPTK.Text, child);
                    searchTK = @"select TenSP,TenChiTiet,TonKho from dbo.KTam_TK where MaSP='" + MaSP1 + "'";
                }
                if (cb_MaSPTK.Text != "" & cb_MaCTTK.Text != "")
                {
                    MaCT1 = prs.substring_right(cb_MaCTTK.Text, child);
                    searchTK = @"select TenSP,TenChiTiet,TonKho from dbo.KTam_TK where MaCT='" + MaCT1 + "'";
                }
                DataSet ds = prs.dts(searchTK);
                if (ds.Tables[0].Rows.Count == 0)
                    MessageBox.Show("Không có dữ liệu");
                else
                {
                    dataGridView5.DataSource = ds.Tables[0];
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void bt_searchTK_Click(object sender, EventArgs e)
        {
            search_TK();
        }

        private void cb_MaSPTK_SelectedIndexChanged(object sender, EventArgs e)
        {
            Process prs = new Process();
            FormProcess Frp = new FormProcess();
            MaSP1 = prs.substring_right(cb_MaSPTK.Text, child);
            cb_MaCTTK.Items.Clear();
            cb_MaCTTK.Text = "";
            string sql_load = @"select MaChiTiet,TenChiTiet from dbo.ChiTietSP where MaSP='" + MaSP1 + "'";
            Frp.cb1(cb_MaCTTK, sql_load, 1, 0);
        }
        private void report_XKTam()
        {
            try
            {
                if (txt_Ngayoutput.Text != "")
                {
                    Process prs = new Process();
                    Ngay1 = txt_Ngayoutput.Text;
                    string[] temp = Ngay1.Split('/');
                    Ngay1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                    string print_XKTam = @"select dbo.ChiTietSP.TenSP,dbo.ChiTietSP.TenChiTiet,dbo.ChiTietSP.LoaiGo,qry1.Serial as Serial_NK,qry1.SLXuat as SoLuong,qry1.SoKH as MaKeHoach,LyDo as LyDoNhap,qry1.SoKH as SoKhoi,LyDo as LyDoNhap,Convert(varchar(8),NgayInsert,108) as DVT
                                        from (select MaCT,Serial,SLXuat,SoKH,LyDo,NgayInsert from dbo.KV4_KTam ";
                    if (cb_MaSPoutput.Text != "")
                    {
                        if (cb_MaCToutput.Text == "")
                        {
                            MaSP1 = prs.substring_right(cb_MaSPoutput.Text, child);
                            print_XKTam += @"          where SLXuat is not null and Ngay>='" + Ngay1 + " 00:00:00' and Ngay<='" + Ngay1 + " 23:59:59') as qry1 inner join dbo.ChiTietSP on qry1.MaCT=dbo.ChiTietSP.MaChiTiet and ChiTietSP.MaSP='"+MaSP1+"' order by qry1.Serial";
                        }
                        else
                        {
                            print_XKTam += @" where SLXuat is not null and Ngay>='" + Ngay1 + " 00:00:00' and Ngay<='" + Ngay1 + " 23:59:59' and MaCT='" + MaCT1 + "') as qry1 inner join dbo.ChiTietSP on qry1.MaCT=dbo.ChiTietSP.MaChiTiet order by qry1.Serial";
                        }

                    }
                    else
                    {
                        print_XKTam += @"          where SLXuat is not null and Ngay>='" + Ngay1 + " 00:00:00' and Ngay<='" + Ngay1 + " 23:59:59') as qry1 inner join dbo.ChiTietSP on qry1.MaCT=dbo.ChiTietSP.MaChiTiet order by qry1.Serial";
                    }
                    DataSet ds = prs.dts(print_XKTam);
                    Fr_Report FrR = new Fr_Report();
                    Ngay1 = txt_Ngayoutput.Text;
                    FrR.report_KV4XKTam(ds, Ngay1);
                    FrR.Show();
                    ds.Clear();

                }
                else
                    MessageBox.Show("Chọn ngày cần in");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        private void report_NKTam()
        {
            try
            {
                if (txt_Ngayinput.Text != "")
                {
                    Process prs = new Process();
                    Ngay1 = txt_Ngayinput.Text;
                    string[] temp = Ngay1.Split('/');
                    Ngay1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                    string print_NKTam = @"select dbo.ChiTietSP.TenSP,dbo.ChiTietSP.TenChiTiet,dbo.ChiTietSP.LoaiGo,qry1.Serial as Serial_NK,qry1.SLNhap as SoLuong,qry1.SoKH as MaKeHoach,(dbo.ChiTietSP.ChieuDaySC*dbo.ChiTietSP.ChieuRongSC*dbo.ChiTietSP.ChieuDaiSC)*qry1.SLNhap/1000000000 as SoKhoi,convert(varchar(8),NgayInsert,108) as DVT,LyDo as LyDoNhap
                                        from (select MaCT,Serial,SLNhap,SoKH,LyDo,NgayInsert from dbo.KV4_KTam ";
                    if (cb_MaSPinput.Text != "")
                    {
                        MaSP1 = prs.substring_right(cb_MaSPinput.Text, child);
                        if (cb_MaCTinput.Text == "")
                        {
                            print_NKTam += @"
                                        where SLNhap is not null and Ngay>='" + Ngay1 + " 00:00:00' and Ngay<='" + Ngay1 + " 23:59:59') as qry1 inner join dbo.ChiTietSP on qry1.MaCT=dbo.ChiTietSP.MaChiTiet where ChiTietSP.MaSP='"+MaSP1+"' order by qry1.Serial";
                            //MessageBox.Show(print_NKTam);
                        }
                        else
                        {
                            MaCT1=prs.substring_right(cb_MaCTinput.Text, child);
                            print_NKTam += @" where SLNhap is not null and Ngay>='" + Ngay1 + " 00:00:00' and Ngay<='" + Ngay1 + " 23:59:59' and MaCT='" + MaCT1 + "') as qry1 inner join dbo.ChiTietSP on qry1.MaCT=dbo.ChiTietSP.MaChiTiet order by qry1.Serial";
                        }
                    }
                    else
                    {
                        print_NKTam += @"
                                        where SLNhap is not null and Ngay>='" + Ngay1 + " 00:00:00' and Ngay<='" + Ngay1 + " 23:59:59') as qry1 inner join dbo.ChiTietSP on qry1.MaCT=dbo.ChiTietSP.MaChiTiet order by qry1.Serial";
                    }
                    DataSet ds = prs.dts(print_NKTam);
                    Fr_Report FrR = new Fr_Report();
                    Ngay1 = txt_Ngayinput.Text;
                    FrR.report_KV4NKTam(ds, Ngay1);
                    FrR.Show();
                    ds.Clear();
                }
                else
                    MessageBox.Show("Chọn ngày cần in");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_printreport_Click(object sender, EventArgs e)
        {
            try
            {
                DataSet ds = new DataSet();
                ds = report_search();
                Fr_Report FrR = new Fr_Report();
                Ngay_start1 = txt_NgayStart.Text;
                Ngay_End1 = " - "+txt_Ngayend.Text;
                FrR.report_KTamTH(ds,Ngay_start1,Ngay_End1);
                FrR.Show();
                ds.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_printinput_Click(object sender, EventArgs e)
        {
            report_NKTam();
        }

        private void bt_printoutput_Click(object sender, EventArgs e)
        {
            report_XKTam();
        }
        private DataSet report_search()
        {
            Process prs = new Process();
            DataSet ds = new DataSet();
            SqlConnection Conn = prs.Connect();
            Conn.Open();
            SqlCommand cmd = new SqlCommand();

            cmd.Connection = Conn;
            cmd.CommandType = CommandType.StoredProcedure;
            string[] temp = txt_NgayStart.Text.Split('/');
            Ngay_start1 = temp[1] + "/" + temp[0] + "/" + temp[2] + " 00:00:00";
            string[] temp2 = txt_Ngayend.Text.Split('/');
            Ngay_End1 = temp2[1] + "/" + temp2[0] + "/" + temp2[2] + " 23:59:59";
            cmd.CommandText = "prc_KV3_TH";
            if (cb_MaSPReport.Text == "")
            {
                cmd.Parameters.AddWithValue("@datebegin", Ngay_start1);
                cmd.Parameters.AddWithValue("@dateend", Ngay_End1);
                cmd.Parameters.AddWithValue("@check", "0");
                cmd.Parameters.AddWithValue("@MaSP", "0");
            }
            if (cb_MaSPReport.Text != "")
            {
                MaSP1 = prs.substring_right(cb_MaSPReport.Text, child);
                if (MaSP1 == "")
                    MessageBox.Show("Nhập sai thông tin SP");
                else
                {
                    cmd.Parameters.AddWithValue("@datebegin", Ngay_start1);
                    cmd.Parameters.AddWithValue("@dateend", Ngay_End1);
                    cmd.Parameters.AddWithValue("@check", "1");
                    cmd.Parameters.AddWithValue("@MaSP", MaSP1);
                }
            }
            ds = prs.dts_sql(cmd);
            return ds;
        }

        private void bt_searchreport_Click(object sender, EventArgs e)
        {
            try
            {
                DataSet ds = new DataSet();
                ds = report_search();
                dataGridView6.DataSource = ds.Tables[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void ExportExcel(DataTable dt, string sheetName)
        {

            Microsoft.Office.Interop.Excel.Application ExcelObj = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(@"C:\\Huynh\\KV4_KTam.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, false, Microsoft.Office.Interop.Excel.XlCorruptLoad.xlNormalLoad);
            Microsoft.Office.Interop.Excel.Sheets sheet = theWorkbook.Worksheets;
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheet.get_Item(1);
            //worksheet.Activate();
            object[,] arr = new object[dt.Rows.Count, dt.Columns.Count];
            //Chuyển dữ liệu từ DataTable vào mảng đối tượng
            for (int r = 0; r < dt.Rows.Count; r++)
            {
                DataRow dr = dt.Rows[r];
                for (int c = 0; c < dt.Columns.Count; c++)
                {
                    //DataRow dr = dt.Rows[r];
                    arr[r, c] = dr[c];
                }
            }

            //Thiết lập vùng điền dữ liệu
            int rowStart = 6;
            int columnStart = 1;

            int rowEnd = rowStart + dt.Rows.Count - 1;
            //int rowEnd = rowStart + dt.Columns.Count - 1;

            int columnEnd = columnStart + dt.Columns.Count - 1;
            //int columnEnd = dt.Rows.Count - 1 + columnStart;

            // Ô bắt đầu điền dữ liệu
            Microsoft.Office.Interop.Excel.Range c1 = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[rowStart, columnStart];
            // Ô kết thúc điền dữ liệu
            Microsoft.Office.Interop.Excel.Range c2 = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[rowEnd, columnEnd];
            // Lấy về vùng điền dữ liệu
            Microsoft.Office.Interop.Excel.Range range = worksheet.get_Range(c1, c2);

            //Điền dữ liệu vào vùng đã thiết lập
            range.Value2 = arr;
            //range.Columns.AutoFit();
            range.Borders.LineStyle = Microsoft.Office.Interop.Excel.Constants.xlSolid;
            //theWorkbook=theWorkbook.Open("C:\\test.xlsx");
            //worksheet = ("sheet1");
            //range.Activate();
            object misValue = System.Reflection.Missing.Value;
            theWorkbook.Close(true, misValue, misValue);
            ExcelObj.Quit();

        }

        private void bt_excelreport_Click(object sender, EventArgs e)
        {
            try
            {
            Process prs = new Process();
            string Search = null;
                
            
          
                    string[] temp = txt_NgayStart.Text.Split('/');
                    Ngay_start1 = temp[1] + "/" + temp[0] + "/" + temp[2]+" 00:00:00";
                    string[] temp2 = txt_Ngayend.Text.Split('/');
                    Ngay_End1 = temp2[1] + "/" + temp2[0] + "/" + temp2[2]+" 23:59:59";
                    //SoKH1 = txt_SoKHReport.Text;
                    Search = @"SELECT [Serial],[MaCT],[SoBB],[SoKH],[LoaiGo],[SLNhap],[SLXuat],[Ngay],[GhiChu],[LyDo]
                            FROM [dbo].[KV4_KTam] where Ngay>='" + Ngay_start1 + "' and Ngay<='" + Ngay_End1 + "'";
             
          
            DataSet ds = prs.dts(Search);
            prs.ExportExcel(ds.Tables[0], "C:\\Huynh\\KV4_KTam.xlsx", 6, 1);
            ds.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void Users(string Users)
        {
            lb_user.Text = Users;
        }

        private void FrKV4_KTam_KeyDown(object sender, KeyEventArgs ex)
        {
            if (ex.KeyData == Keys.Enter)
            {
                SendKeys.Send("{TAB}");
            }
            if (ex.KeyCode == Keys.F11)
            {
                bt_saveinput_Click(null, null);
            }
            if (ex.KeyCode == Keys.F12)
            {
                bt_saveoutput_Click(null, null);
            }
            if (ex.KeyCode == Keys.F5)
            {
                TD_KeHoach();
            }
        }

        private void cb_MaCToutput_SelectedIndexChanged(object sender, EventArgs e)
        {
            TonKho();
        }

        private void lb_user_TextChanged(object sender, EventArgs e)
        {
            Check_User();

        }

        private void txt_SLoutput_Leave(object sender, EventArgs e)
        {
            try
            {
                check_TonKho();
            }
            catch
            {
            }
        }

        private void dataGridView1_DoubleClick_1(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 1)
            {
                try
                {
                    int r = dataGridView1.CurrentCell.RowIndex;
                    //MessageBox.Show(r.ToString());
                    Tong1 = double.Parse(lb_Tong.Text) - double.Parse(dataGridView1.Rows[r].Cells["SLInput"].Value.ToString());
                    lb_Tong.Text = string.Format("{0:###,###}", Tong1);
                    dataGridView1.Rows.RemoveAt(r);
                    //MessageBox.Show("aaaa");
                    int j = dataGridView1.Rows.Count - 1;
                    dataGridView1.CurrentCell = dataGridView1.Rows[j].Cells["MaCTinput"];
                    
                }
                catch (Exception ex)
                { MessageBox.Show(ex.Message); }
            }
            if (dataGridView1.Rows.Count == 1)
                lb_Tong.Text = "0";
        }

        private void dataGridView3_DoubleClick_1(object sender, EventArgs e)
        {
            if (dataGridView3.Rows.Count > 1)
            {
                try
                {
                    int r = dataGridView3.CurrentCell.RowIndex;
                    //MessageBox.Show(r.ToString());
                    Tong1 = double.Parse(lb_TongXuat.Text) - double.Parse(dataGridView3.Rows[r].Cells["SLoutput"].Value.ToString());
                    lb_TongXuat.Text = string.Format("{0:###,###}", Tong1);
                    dataGridView3.Rows.RemoveAt(r);
                    //MessageBox.Show("aaaa");
                    int j = dataGridView3.Rows.Count - 1;
                    dataGridView3.CurrentCell = dataGridView3.Rows[j].Cells["MaCToutput"];
                }
                catch (Exception ex)
                { MessageBox.Show(ex.Message); }
            }
            if (dataGridView3.Rows.Count == 1)
            {
                lb_TongXuat.Text = "0";
            }
        }

        
        private void check_SLKH()
        {

        }

       

        private void cb_SoKHoutput_Leave(object sender, EventArgs e)
        {
            FormProcess Frp = new FormProcess();
            Process prs = new Process();
            SqlConnection Conn = prs.Connect();
            Conn.Open();
            SqlCommand cmd = new SqlCommand();
            try
            {
                SoKH1 = prs.substring_right(cb_SoKHoutput.Text, child);
                string check_SL = null;
                check_SL = @"select SLTheoDoi from dbo.KH_TheoDoi where ID='" + SoKH1 + "'";
                cmd.CommandText = check_SL;
                cmd.Connection = Conn;
                lb_SLKH.Text = cmd.ExecuteScalar().ToString();
            }
            catch
            {
                //MessageBox.Show(ex.Message);
                cb_SoKHoutput.Text = "";
                lb_SLKH.Text = "0";
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }
        private void TD_KeHoach()
        {
            string selectKH = @"select ChiTietSP.TenSP,ChiTietSP.TenChiTiet,KV4_SLXuat.NgayXP,left(KH_TheoDoi.ID_KeHoach,5) as MaKH,KH_TheoDoi.SLKH as SoLuong,isnull(KV4_SLXuat.SLXuat,0) as SLXuat,KH_TheoDoi.SLKH-isnull(KV4_SLXuat.SLXuat,0) as SLTon 
                                from (select distinct(ID_KeHoach) as SoKH from dbo.KH_TheoDoi where SLTheoDoi>0 and ID_KeHoach like '%KV3%') as KH_Chon inner join dbo.KH_TheoDoi on KH_TheoDoi.ID_KeHoach=KH_Chon.SoKH
                                left join (select KV4_KTam.SoKH,sum(SLXuat) as SLXuat,min(NgayInsert) as NgayXP from dbo.KV4_KTam where SoKH is not null group by SoKH) as KV4_SLXuat on KV4_SLXuat.SoKH=KH_TheoDoi.ID 
                                inner join ChiTietSP on ChiTietSP.MaChiTiet=KH_TheoDoi.MaCT";
            Process prs = new Process();
            DataSet ds = prs.dts(selectKH);
            Fr_Report FrR = new Fr_Report();
            //Ngay1 = txt_Ngayinput.Text;
            FrR.report_TDKH_Nhung(ds);
            FrR.Show();
            ds.Clear();
            

        }
        private void search_KH()
        {
            string searchKH = @"select ChiTietSP.TenSP,ChiTietSP.TenChiTiet,left(KH_TheoDoi.ID_KeHoach,5) as MaKH,qry1.NgayXP,qry1.SLXuat,KH_TheoDoi.SLKH as SoLuong,KH_TheoDoi.SLKH-isnull(qry1.SLXuat,0) as SLTon
                                from 
                                KH_TheoDoi left join (select SoKH,sum(SLXuat) as SLXuat,min(NgayInsert) as NgayXP from dbo.KV4_KTam group by SoKH) as qry1 on KH_TheoDoi.ID=qry1.SoKH 
                                inner join ChiTietSP on KH_TheoDoi.MaCT=ChiTietSP.MaChiTiet where KH_TheoDoi.ID_KeHoach like '%KV3%'";
            Process prs = new Process();
            DataSet ds = new DataSet();
            try
            {
                if (txt_searchKH.Text == "")
                {
                    ds = prs.dts(searchKH);

                }
                else
                {
                    searchKH += " and KH_TheoDoi.ID_KeHoach like '%" + txt_searchKH.Text + "%'";
                    ds = prs.dts(searchKH);
                }
                Fr_Report FrR = new Fr_Report();
                //Ngay1 = txt_Ngayinput.Text;
                FrR.report_TDKH_Nhung(ds);
                FrR.Show();
                ds.Clear();
            }
            catch
            {
                MessageBox.Show("Kiểm tra lại thông tin tìm kiếm");
            }
        }

        private void bt_searchKH_Click(object sender, EventArgs e)
        {
            search_KH();
        }

        private void cb_LyDoNhap_Leave(object sender, EventArgs e)
        {
            Process prs = new Process();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();
            Conn.Open();
            cmd.Connection = Conn;
            try
            {
                if (cb_MaCTinput.Text != "")
                {

                    MaCT1 = prs.substring_right(cb_MaCTinput.Text, child);
                    if (MaCT1 != "")
                    {
                        if (cb_LyDoNhap.Text == "Lắp Ráp")
                        {
                            txt_SoBBinput.Enabled = true;
                            string_temp = @"SELECT [ID] FROM [dbo].[KH_Theodoi]
                                where SLTheoDoi>0 and ID_KeHoach like '%KV2XLR%' and MaCT='" + MaCT1 + "'";
                            cmd.CommandText = string_temp;
                            txt_SoBBinput.Items.Clear();
                            SqlDataReader rd = cmd.ExecuteReader();
                            while (rd.Read())
                            {
                                txt_SoBBinput.Items.Add(rd[0].ToString());
                            }
                            rd.Close();
                        }
                        else
                        {
                            txt_SoBBinput.Enabled = false;
                            txt_SoBBinput.Text = "";
                        }
                    }
                    else
                        MessageBox.Show("Nhập sai thông tin chi tiết");
                }
                else
                    MessageBox.Show("Bạn chưa nhập mã chi tiết");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }

        private void txt_SoBBinput_Leave(object sender, EventArgs e)
        {
            Process prs = new Process();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();
            Conn.Open();
            cmd.Connection = Conn;
            try
            {
                if (cb_LyDoNhap.Text == "Lắp Ráp")
                {
                    if (txt_SoBBinput.Text != "")
                    {
                        string_temp = @"select SLTheoDoi from dbo.KH_TheoDoi where ID='" + txt_SoBBinput.Text + "'";
                        cmd.CommandText = string_temp;
                        lb_SLPhieu.Text = cmd.ExecuteScalar().ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                lb_SLPhieu.Text = "0";
            }
            finally
            {
                cmd.Dispose();
                Conn.Close();
            }
        }

        private void txt_SLinput_Leave(object sender, EventArgs e)
        {
            try
            {
                if (txt_SoBBinput.Enabled == true)
                {
                    if (double.Parse(txt_SLinput.Text) > double.Parse(lb_SLPhieu.Text))
                    {
                        MessageBox.Show("Số lượng nhập đã vượt quá số lượng trong phiếu");
                        txt_SLinput.Text = "";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void add_grid_chuyen()
        {
            string TenSP2=null, TenCT2, MaCT2=null;
            int k = 0,j=0;
            try
            {
                Process prs = new Process();
                TenSP1 = prs.substring_left(cb_MaSP_C.Text, child);
                TenCT1 = prs.substring_left(cb_MaCT_C.Text, child);
                MaCT1 = prs.substring_right(cb_MaCT_C.Text, child);
                
                TenSP2 = prs.substring_left(cb_MaSP_N.Text, child);
                TenCT2 = prs.substring_left(cb_MaCT_N.Text, child);
                MaCT2 = prs.substring_right(cb_MaCT_N.Text, child);
               

                if (TenSP1 == "" || MaCT1 == "" || txt_SLChuyen.Text == "" ||TenSP2 == "" || MaCT2 == "")
                {
                    MessageBox.Show("Thông Tin Nhập Không Chính Xác Hoặc Thiếu");
                }
                else
                {
                    i = 0;
                    if (dataGridView7.Rows.Count > 1)
                    {
                        while (i < dataGridView7.Rows.Count - 1)
                        {
                            if (MaCT1 != dataGridView7.Rows[i].Cells["MaCT_C"].Value.ToString())
                                i++;
                            else
                                break;
                        }
                    }
                    if (dataGridView7.Rows.Count == 1 || i == dataGridView7.Rows.Count - 1)
                    {
                        k = cb_MaCT_C.Items.Count - 1;
                        while (k >= 0)
                        {

                            if (MaCT1 == prs.substring_right(cb_MaCT_C.Items[k].ToString(), child))
                                break;
                            else
                                k--;
                        }
                      
                       
                        if (k >= 0)
                        {
                            //SoBB1 = txt_SoBBinput.Text.Trim();
                            //SL1 = txt_SLInput.Text.Trim();
                            Ngay1 = txt_Ngay_C.Text.Trim();
                            SLNhap1 = "-" + txt_SLChuyen.Text;
                            string[] temp = txt_Ngay_C.Text.Split('/');
                            NgayInsert1 = temp[1] + "/" + temp[0] + "/" + temp[2];

                            dataGridView7.Rows.Add(TenSP1, MaCT1, TenCT1, SLNhap1, Ngay1, NgayInsert1);
                            SLNhap1 = txt_SLChuyen.Text;
                            dataGridView7.Rows.Add(TenSP2, MaCT2, TenCT2, SLNhap1, Ngay1, NgayInsert1);
                            j = dataGridView7.Rows.Count - 1;
                            dataGridView7.CurrentCell = dataGridView7.Rows[j].Cells[0];
                            dataGridView7.FirstDisplayedCell = dataGridView7.Rows[j].Cells[0];
                            prs.formatcolordatagrid(dataGridView7);
                            //prs.reset_txt(groupPanel1);
                            txt_SLChuyen.Text = "";
                           
                            cb_MaSP_C.Focus();
                          
                            cb_MaSP_N.Text = "";
                            cb_MaCT_C.Text = "";
                           
                        }
                        else
                            MessageBox.Show("Kiểm tra lại Mã CT hoặc Mã KH nhập");
                    }
                    else
                        MessageBox.Show("Chi Tiết này đã có trong DS phía dưới");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void save_Chuyen()
        {

            Data dta = new Data();
            SqlConnection Conn = dta.Connect();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "Tran_Ins_Up_KTam";
            cmd.CommandType = CommandType.StoredProcedure;
            Conn.Open();
            cmd.Connection = Conn;

            try
            {
                UserXuat = "";
                if (dataGridView7.Rows.Count > 1)
                {

                    for (i = dataGridView7.Rows.Count - 2; i >= 0; i--)
                    {
                        //MaCT1 = "'Null'";

                        MaCT1 = dataGridView7.Rows[i].Cells["MaCT_C"].Value.ToString();
                        //SoKH1 = dataGridView7.Rows[i].Cells["KH_C"].Value.ToString();

                        SLNhap_d = double.Parse(dataGridView7.Rows[i].Cells["SL_C"].Value.ToString());

                        //flag1 = dataGridView7.Rows[i].Cells["flag_C"].Value.ToString();
                        Ngay1 = dataGridView7.Rows[i].Cells["NgayInsert_C"].Value.ToString();
                        UserNhap = lb_user.Text;
                        
                        cmd.Parameters.AddWithValue("@MaCT", MaCT1);
                        cmd.Parameters.AddWithValue("@SoBB", "");
                        cmd.Parameters.AddWithValue("@LoaiGo", "");
                        cmd.Parameters.AddWithValue("@SLNhap", SLNhap_d);
                        cmd.Parameters.AddWithValue("@Ngay", Ngay1);
                        cmd.Parameters.AddWithValue("@GhiChu", "Chuyển");
                        cmd.Parameters.AddWithValue("@LyDo", "Chuyển");
                        cmd.Parameters.AddWithValue("@UserNhap", UserNhap);
                        cmd.Parameters.AddWithValue("@SLTheoDoi", "0");
                        cmd.Parameters.AddWithValue("@ID", "");
                        cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        dataGridView7.Rows.RemoveAt(i);
                    }
                    MessageBox.Show("Dữ Liệu được lưu thành công");
                    lb_Tong.Text = "0";
                    dta.reset_txt(groupPanel1);
                    cb_MaCT_C.Text = "";
                    cb_MaSP_C.Text = "";
                    cb_MaSP_N.Text = "";
                    cb_MaCT_N.Text = "";
                    cb_MaSP_C.Focus();
                }
            }
            catch (Exception ex)
            {
                string s = "insert duplicate key";
                string FK = "FOREIGN KEY constraint";
                string s1 = ex.Message.ToString();
                if (s1.Contains(s))
                { MessageBox.Show("Insert không thành công \n" + "Mã đã tồn tại "); }
                else if (s1.Contains(FK))
                { MessageBox.Show("Nhập sai thông tin trong Combobox"); }
                else
                    MessageBox.Show(ex.Message);
                MessageBox.Show("Đã xảy ra lỗi khi thêm dữ liệu, vui lòng kiểm tra lại");
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }
        private void buttonX2_Click(object sender, EventArgs e)
        {
            save_Chuyen();
        }

        private void cb_MaSP_C_SelectedIndexChanged(object sender, EventArgs e)
        {
            Process prs = new Process();
            FormProcess Fr = new FormProcess();
            MaSP1 = prs.substring_right(cb_MaSP_C.Text, child);
            cb_MaCT_C.Items.Clear();
            //cb_MaCTinput.Text = "";
            cb_MaCT_C.Text = "";
            string_temp = @"select TenChiTiet,MaChiTiet from dbo.Load_CTSP_Mua";
            Fr.cb1(cb_MaCT_C, string_temp, 0, 1);
            /*for (i = dataGridView_LoadSP.Rows.Count - 2; i >= 0; i--)
            {
                if (MaSP1 == dataGridView_LoadSP.Rows[i].Cells[0].Value.ToString())
                {
                    cb_MaCT_C.Items.Add(dataGridView_LoadSP.Rows[i].Cells[1].Value.ToString());
                }
            }*/

        }

        private void cb_MaSP_N_SelectedIndexChanged(object sender, EventArgs e)
        {
            Process prs = new Process();

            MaSP1 = prs.substring_right(cb_MaSP_N.Text, child);
            cb_MaCT_N.Items.Clear();
            //cb_MaCTinput.Text = "";
            cb_MaCT_N.Text = "";
            for (i = dataGridView_LoadSP.Rows.Count - 2; i >= 0; i--)
            {
                if (MaSP1 == dataGridView_LoadSP.Rows[i].Cells[0].Value.ToString())
                {
                    cb_MaCT_N.Items.Add(dataGridView_LoadSP.Rows[i].Cells[1].Value.ToString());
                }
            }
        }

        private void buttonX1_Click(object sender, EventArgs e)
        {
            add_grid_chuyen();
        }

        private void cb_MaCT_C_SelectedIndexChanged(object sender, EventArgs e)
        {
             Process prs = new Process();
            FormProcess Frp = new FormProcess();
            SqlConnection Conn = prs.Connect();

            SqlCommand cmd = new SqlCommand();
            Conn.Open();
            cmd.Connection = Conn;
            try
            {

                MaCT1 = prs.substring_right(cb_MaCT_C.Text, child);
                string TonKho = @"select TonKho from dbo.KTam_TK where MaCT='" + MaCT1 + "'";
                cmd.CommandText = TonKho;
                lb_TonKho_C.Text = cmd.ExecuteScalar().ToString();
            }
            catch
            {
                lb_TonKho_C.Text = "0";
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }

        private void txt_SLChuyen_Leave(object sender, EventArgs e)
        {
            try
            {
                SLXuat_d = double.Parse(txt_SLChuyen.Text);
                TK_KTG = double.Parse(lb_TonKho_C.Text);
                if (SLXuat_d > TK_KTG)
                {
                    MessageBox.Show("SL xuất không vượt quá SL Tồn Kho");
                    txt_SLChuyen.Text = "";
                }
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process prs = new Process();
            Ngay1 = date_reportNKNgay.Text;
            string[] temp = Ngay1.Split('/');
            Ngay1 = temp[1] + "/" + temp[0] + "/" + temp[2];
            string_temp = @"select dbo.ChiTietSP.TenSP,dbo.ChiTietSP.TenChiTiet,dbo.ChiTietSP.LoaiGo,qry1.SLNhap as SoLuong,LyDo as LyDoNhap
                                        from (select MaCT,sum(SLNhap) as SLNhap,LyDo from dbo.KV4_KTam 
                                        where SLNhap is not null and Ngay>='"+Ngay1+" 00:00:00' and Ngay<='"+Ngay1+" 23:59:59' group by MaCT,LyDo) as qry1 inner join dbo.ChiTietSP on qry1.MaCT=dbo.ChiTietSP.MaChiTiet";
            DataSet ds = prs.dts(string_temp);
            Fr_Report FrR = new Fr_Report();
            Ngay1 = date_reportNKNgay.Text;
            FrR.report_KV4Verni(ds, Ngay1);
            FrR.Show();
            ds.Clear();
        }

        private void labelX26_DoubleClick(object sender, EventArgs e)
        {
            txt_SoPhieu_print.Visible = true;
        }

        private void txt_SoPhieu_print_Leave(object sender, EventArgs e)
        {
            if (txt_SoPhieu_print.Text != "")
            {
                //SqlConnection Conn = new SqlConnection();
                Process prs = new Process();
                
                DataSet ds = new DataSet();
                try
                {
                    string_temp = @"select Serial as Serial_NK,Load_CTSP_Mua.TenSP,Load_CTSP_Mua.TenChiTiet,ChungTu,left(SoKH,5) as SoKhoi,SLXuat as SoLuong,convert(varchar(10),Ngay,103) as Ngay,LyDo as LyDoNhap,Load_CTSP_Mua.LoaiGo From dbo.KV4_KTam inner join dbo.Load_CTSP_Mua on Load_CTSP_Mua.MaChiTiet=MaCT where ChungTu="+txt_SoPhieu_print.Text;
                    ds = prs.dts(string_temp);
                    Fr_Report FrR = new Fr_Report();
                    //Ngay1 = txt_Ngayoutput.Text;
                    FrR.KV4XKTam(ds);
                    FrR.Show();
                    txt_SoPhieu_print.Visible = false;
                    //ds.Clear();

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                   
                    ds.Clear();
                }

            }
        }

        private void FrKV3_KTam_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Control)
            {
                /*if (e.KeyCode.Equals(Keys.N))
                {
                    rd_GiaoSoChe.Enabled = true;
                    rd_ChuyenNoiBo.Enabled = true;
                }*/
                /* if (e.KeyCode.Equals(Keys.G))
                 {
                     maskedTextBox1.Visible = true;
                     maskedTextBox2.Visible = true;
                 }*/
                if (e.KeyCode.Equals(Keys.P))
                {
                    txt_SoPhieu_print_Leave(null, null);
                }
            }
        }

    }
}
